/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rw.table.editor;

import com.rw.table.TableInfo;
import com.rw.table.formatter.ICellFormatter;
import java.awt.Component;
import java.text.ParseException;
import javax.swing.JTextField;

/**
 *
 * @author Rene Tapia
 */
public class TextCellEditor extends ACellEditor {

    private JTextField text;

    public TextCellEditor() {
        this.text = new JTextField();
        this.text.setOpaque(true);
    }

    @Override
    public Component getComponent(TableInfo info) {
        Object value = info.getValue();
        ICellFormatter formatter = info.getFormatter();

        String strValue = value != null ? formatter.format(value) : "";
        this.text.setText(strValue);

        int align = formatter.getAlign();
        this.text.setHorizontalAlignment(align);

        this.text.setText(strValue);
        this.text.selectAll();

        return text;
    }

    @Override
    public Object getCellEditorValue(ICellFormatter formatter) {
        String strValue = this.text.getText();
        try {
            return formatter.parse(strValue);
        } catch (ParseException e) {
            return null;
        }
    }

    public JTextField getText() {
        return text;
    }
}
